package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Service
public class AuthFilter implements GlobalFilter, Ordered {
    //过滤器执行逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取URL地址
        String url = request.getURI().getPath();
        //判断是否需要鉴权
        //如果请求的URL中包含login直接放行
        if (url.contains("/login")) {
            return chain.filter(exchange);
        }
        //否则需要拦截
        //获取请求头
        String token = request.getHeaders().getFirst("token");
        //判断请求头中是否包含token
        //没有token返回未授权状态
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //有token,需要通过jwt验证token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if (result==-1||result==0) {
                //token有效,获取当前token中用户id,将userID放到请求头中转发到后端的微服务,放行
                Object userId = claims.get("userId");
                Object userName = claims.get("userName");
                request.mutate().header("userId", userId.toString());
                request.mutate().header("userName", userName.toString());
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            //记录错误日志
            log.error(e.getMessage());

        }
        //其他情况统一返回401未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
//过滤器的执行顺序,数字越小,先执行
    @Override
    public int getOrder() {
        return 0;
    }
}
